<template>
  <div class="app-container">
    <!-- 新增：招聘计划选择 -->
    <el-form label-width="120px">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="选择招聘计划">
            <el-select v-model="selectedPlanId"
                       :disabled="activePlans.length <= 1"
                       placeholder="请选择招聘计划"
                       clearable
                       style="width: 100%"
                       @change="handlePlanChange">
              <el-option
                v-for="plan in activePlans"
                :key="plan.planId"
                :label="plan.planName"
                :value="plan.planId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- 刷新、折叠搜索框按钮 -->
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        <el-button type="primary" @click="handleMyApply()">我的报名</el-button>
      </el-row>
    </el-form>
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="岗位编码" prop="positionCode">-->
<!--        <el-input-->
<!--          v-model="queryParams.positionCode"-->
<!--          placeholder="请输入岗位编码"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="公司名称" prop="companyName">-->
<!--        <el-input-->
<!--          v-model="queryParams.companyName"-->
<!--          placeholder="请输入公司名称"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="岗位名称" prop="positionName">
        <el-input
          v-model="queryParams.positionName"
          placeholder="请输入岗位名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="招聘数量" prop="positionNumber">-->
<!--        <el-input-->
<!--          v-model="queryParams.positionNumber"-->
<!--          placeholder="请输入招聘数量"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="报名年龄" prop="ageLimit">
        <el-input
          v-model="queryParams.ageLimit"
          placeholder="请输入您的年龄"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="岗位性质" prop="positionNature">-->
<!--        <el-input-->
<!--          v-model="queryParams.positionNature"-->
<!--          placeholder="请输入岗位性质"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="薪酬范围">
        <el-col :span="10">
          <el-input
            v-model="queryParams.minSalary"
            placeholder="最低薪酬"
            clearable
            @keyup.enter.native="handleQuery"
            prop="minSalary"
          >

          </el-input>
        </el-col>
        <el-col class="line" :span="2" style="text-align: center;">-</el-col>
        <el-col :span="10">
          <el-input
            v-model="queryParams.maxSalary"
            placeholder="最高薪酬"
            clearable
            @keyup.enter.native="handleQuery"
            prop="maxSalary"
          >
            <template slot="append">元/月</template>
          </el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="学历要求" prop="educationaRequirements">
         <el-select
            v-model="queryParams.educationaRequirements"
            placeholder="请选择学历要求"
            clearable
            style="width: 100%"
            @keyup.enter.native="handleQuery"
          >
            <el-option label="不限" value="不限"></el-option>
            <el-option label="初中" value="初中"></el-option>
            <el-option label="高中" value="高中"></el-option>
            <el-option label="大专" value="大专"></el-option>
            <el-option label="本科" value="本科"></el-option>
            <el-option label="硕士" value="硕士"></el-option>
            <el-option label="博士" value="博士"></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="工作地点" prop="location">
        <el-input
          v-model="queryParams.location"
          placeholder="请输入工作地点"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="鉴定专业" prop="major">-->
<!--        <el-input-->
<!--          v-model="queryParams.requiredMajor"-->
<!--          placeholder="请输入职业鉴定专业"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="技能等级" prop="level">-->
<!--        <el-input-->
<!--          v-model="queryParams.requiredLevel"-->
<!--          placeholder="请输入职业技能鉴定等级"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="批次编号" prop="batchNumber"  v-show="false" >
        <el-input
          v-model="queryParams.batchNumber"
          placeholder="请输入批次编号"
          clearable
          @keyup.enter.native="handleQuery"
          disabled
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 带全部岗位的 Tabs -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick" class="job-tabs">
      <el-tab-pane label="全部岗位" name="all">
        <div class="job-list" :style="{ maxHeight: '600px', overflowY: 'auto' }">
          <div v-for="job in paginatedAll" :key="job.positionId" class="job-card" @click="handleApply(job)">
            <!-- 卡片内容 -->
            <!-- 卡片头 -->
            <div class="card-header">
              <span class="job-name">{{ job.positionName }}</span> |
              <span class="job-content">{{ job.workContent }}</span>
              <span class="job-salary">￥{{ job.salary }}</span>
            </div>

            <!-- 卡片内容 -->
            <div class="card-body">
              <span class="badge">{{ job.positionNumber }}人</span>
              <span class="badge">{{ job.location }}</span>
              <span class="badge">{{ job.educationaRequirements }}</span>
              <span class="badge">{{ job.major }}</span>
            </div>

            <!-- 卡片尾 -->
            <div class="card-footer">
              <span class="company-name">{{ job.companyName }}</span>
              <span class="contact-phone">电话：{{ job.contact_phone }}</span>
            </div>
          </div>
        </div>
        <!-- 在 "全部岗位" 分页中 -->
        <pagination
          v-show="totalAll > 0"
          :total="totalAll"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="handlePaginationChange"
        />
      </el-tab-pane>

      <!-- 分类岗位 Tab -->
      <el-tab-pane v-for="(group, nature) in categorizedJobs" :key="nature" :label="nature" :name="nature">
        <div class="job-list" :style="{ maxHeight: '600px', overflowY: 'auto' }">
          <div v-for="job in paginatedCategory(group)" :key="job.positionId" class="job-card" @click="handleApply(job)">
            <!-- 卡片内容 -->
            <!-- 卡片头 -->
            <div class="card-header">
              <span class="job-name">{{ job.positionName }}</span> |
              <span class="job-content">{{ job.workContent }}</span>
              <span class="job-salary">￥{{ job.salary }}</span>
            </div>

            <!-- 卡片内容 -->
            <div class="card-body">
              <span class="badge">{{ job.positionNumber }}人</span>
              <span class="badge">{{ job.location }}</span>
              <span class="badge">{{ job.educationaRequirements }}</span>
              <span class="badge">{{ job.major }}</span>
            </div>

            <!-- 卡片尾 -->
            <div class="card-footer">
              <span class="company-name">{{ job.companyName }}</span>
              <span class="contact-phone">电话：{{ job.contact_phone }}</span>
            </div>
            <!--        <div class="card-footer">-->
            <!--          <el-button size="mini" type="primary" plain icon="el-icon-guide" @click="handleApply(job)">报名</el-button>-->
            <!--        </div>-->
          </div>
        </div>
        <!-- 在每个分类分页中 -->
        <pagination
          v-show="group.length > 0"
          :total="group.length"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="handlePaginationChange"
        />
      </el-tab-pane>
    </el-tabs>

    <!-- 招聘岗位信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span class="el-icon-document">报名申请表</span>
          <!--          <el-button style="float: right;" size="mini" type="danger" @click="goBack">关闭</el-button>-->
        </div>
        <el-tabs tab-position="top" v-model="activeName" @tab-click="handleClick">
          <!--表单信息-->
          <el-tab-pane label="表单信息" name="1">
            <!--初始化流程加载表单信息-->
            <v-form-render :form-data="formRenderData" ref="vFormRef" disabled/>
            <div style="margin-left:15%;margin-bottom: 20px;font-size: 14px;">
              <el-button type="primary" @click="submitForm">提 交</el-button>
              <el-button type="primary" @click="close">取 消</el-button>
            </div>
          </el-tab-pane>
          <!--流程图-->
          <el-tab-pane label="审核流程图" name="2">
            <bpmn-viewer :flowData="flowData"/>
          </el-tab-pane>
        </el-tabs>

      </el-card>

    </el-dialog>


    <!-- 报名信息对话框 -->
    <el-dialog title="我的报名信息" :visible.sync="applyDialogVisible" width="800px" append-to-body>
      <el-form :model="applyInfo" label-width="120px" disabled>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="岗位编码">
              <el-input v-model="applyInfo.positionCode"/>
            </el-form-item>
            <el-form-item label="公司名称">
              <el-input v-model="applyInfo.companyName"/>
            </el-form-item>
            <el-form-item label="岗位名称">
              <el-input v-model="applyInfo.positionName"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="批次编号">
              <el-input v-model="applyInfo.batchNumber"/>
            </el-form-item>
            <el-form-item label="工作地点">
              <el-input v-model="applyInfo.location"/>
            </el-form-item>
            <el-form-item label="报名时间">
              <el-input v-model="applyInfo.createTime"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" @click="cancelMyApply">取消申请</el-button> -->
        <el-button @click="applyDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 修改通知弹窗按钮，增加 disabled 判断 -->
    <el-dialog
      :visible.sync="noticeDialogVisible"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="600px"
      center
      class="notice-dialog"
      :style="{ maxHeight: '90vh' }"
    >
      <div v-if="currentNotice" class="notice-content">
        <h3>{{ currentNotice.noticeTitle }}</h3>
        <div class="notice-body">
          <!-- 修改：使用复选框显示通知内容 -->
          <div
            v-for="(line, index) in noticeLines"
            :key="index"
            class="notice-line"
          >
            <el-checkbox
              v-model="checkedLines[index]"
              @change="() => handleLineCheck(index)"
              class="notice-checkbox"
            >
              <span class="notice-line-content">{{ line }}</span>
            </el-checkbox>
          </div>
        </div>
        <div class="progress-info">
          已读进度: {{ checkedLines.filter(Boolean).length }}/{{ checkedLines.length }}
        </div>
        <div class="countdown">
          阅读剩余时间：{{ countdown }} 秒
        </div>
        <div class="manual-close">
          <el-button
            type="primary"
            @click="closeNotice"
            :disabled="countdown > 0 || !checkedLines.every(checked => checked)"
          >
            关闭通知
          </el-button>
        </div>
      </div>
    </el-dialog>





  </div>
</template>

<script>
import {listAvailable, getAvailable, delAvailable, addAvailable, updateAvailable} from "@/api/system/available";
import {listPlan} from "@/api/system/plan"; // 引入招聘计划接口
import {getToken} from "@/utils/auth";
import {parseTime} from "@/utils";
import {getUser, getUserProfile} from "@/api/system/user";
import {definitionStart, flowXmlAndNode} from "@/api/flowable/definition";
import {flowFormData,stopProcess} from "@/api/flowable/process";


import BpmnViewer from '@/components/Process/viewer';
import {getNextFlowNodeByStart} from "@/api/flowable/todo";
import FlowUser from '@/components/flow/User'
import FlowRole from '@/components/flow/Role'
import {addApply, delApplyByID, getApplyByIdcardAndBatchNumber, haspermit} from "@/api/system/apply";
import {listNotice} from "@/api/system/notice";
import user from "@/store/modules/user";


export default {
  name: "Available",
  components: {
    BpmnViewer,
    FlowUser,
    FlowRole,
  },
  props: {
    user: {
      type: Object
    }
  },
  data() {
    return {

      // 通知弹窗
      noticeDialogVisible: false,
      // 公告表格数据
      noticeList: [],
      currentNotice: null,
      countdown: 30,
      noticeTimer: null,
      currentNoticeIndex: 0,
      // 修改：将 readProgress 和 hasReadToBottom 替换为 checkbox 相关数据
      noticeLines: [], // 通知内容按行分割
      checkedLines: [], // 每行的选中状态


      // 招聘计划相关
      selectedPlanId: null,
      allPlans: [],         // 所有招聘计划
      activePlans: [],      // 当前可选的招聘计划（报名截止时间大于当前时间）

      // 通用数据 岗位相关
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      activeTab: 'all', // 默认选中全部岗位
      availableList: [], // 所有岗位数据
      paginatedAll: [], // 分页后的全部岗位数据
      totalAll: 0, // 全部岗位总数
      queryParams: {
        pageNum: 1,
        pageSize: 30,
        positionCode: null,
        companyName: null,
        workContent: '',
        positionName: null,
        positionNumber: null,
        ageLimit: null,
        positionSort: null,
        positionNature: null,
        salary: null,
        minSalary:null,
        maxSalary:null,
        educationaRequirements: null,
        location: null,
        major: null,
        level: null,
        workExperienceRequirements: null,
        contact_phone: null,
        batchNumber: null,
        status: null,
      },
      // 表单参数
      open: false,
      form: {},
      userForm: {
        userName: '',
        phonenumber: '',
        email: '',
        sex: '',
        status: ''
      },
      applyForm: {//报名表单
        userId: null,
        deptId: null,
        userName: null,
        idcard: null,
        batchNumber: null,
        positionCode: null,
        companyName: null,
        location: null,
        positionName: null
      },


      applyDialogVisible: false,
      applyInfo: {//查询报名信息
        applyId: null,
        positionCode: null,
        positionName: null,
        companyName: null,
        location: null,
        batchNumber: null,
        applyTime: null
      },


      // 导入参数
      upload: {
        open: false,
        title: "",
        isUploading: false,
        updateSupport: 0,
        headers: {Authorization: "Bearer " + getToken()},
        url: process.env.VUE_APP_BASE_API + "/system/available/importData"
      },
      rules: {},
      title: "",

      // 模型xml数据
      flowData: {},
      activeName: '1', // 切换tab标签
      // 查询参数
      queryParams1: {
        deptId: undefined
      },
      // 遮罩层

      deployId: "",  // 流程定义编号
      procDefId: "",  // 流程实例编号
      formRenderData: {},
      variables: [], // 流程变量数据
      taskTitle: '',
      taskOpen: false,
      checkSendUser: false, // 是否展示人员选择模块
      checkSendRole: false,// 是否展示角色选择模块
      checkType: '', // 选择类型
      checkValues: null, // 选中任务接收人员数据
      formData: {}, // 填写的表单数据,
      multiInstanceVars: '', // 会签节点
      formJson: {}, // 表单json
      haspermit:'',   //报名权限
    };
  },
  created() {

    this.getUserInfo();

   this.deployId = "152569";
   this.procDefId = "flow_aunnkak6:4:152572";
    this.token = this.$store.getters.token;

  },
  methods: {

      // 新增：加载通知
    loadNotices() {
      // 获取当前用户ID和当前日期
      const userId = this.userForm.userId;
      const today = new Date().toISOString().split('T')[0];
      const storageKey = `hasViewedNotice_${userId}_${today}`;

      const hasViewed = localStorage.getItem(storageKey);

      if (hasViewed) {
        console.log('该用户今天已读过通知，不再显示');
        return; // 该用户今天已经显示过，不再显示
      }

      listNotice().then(response => {
        console.log('原始通知数据:', response.rows); // 添加日志
        const notices = response.rows.filter(n => n.noticeType === "1");
        console.log('筛选后的通知:', notices); // 添加日志
        if (notices.length > 0) {
          this.noticeList = notices;
          this.currentNotice = notices[0];
          // 初始化通知行
          this.initializeNoticeLines();
          this.noticeDialogVisible = true;
          this.startCountdown();
          // 标记为该用户今天已读
          localStorage.setItem(storageKey, 'true');
        }else {
          console.log('没有符合条件的通知');
        }
      }).catch(error => {
        console.error('加载通知失败:', error);
      });
    },

      // 修改 startCountdown 方法，只显示倒计时，不再自动关闭
      startCountdown() {
        this.countdown = 10;
        if (this.noticeTimer) {
          clearInterval(this.noticeTimer);
        }

        // 不再自动关闭，只显示倒计时状态
        // 仅用于 UI 倒计时显示（不自动关闭）
        this.noticeTimer = setInterval(() => {
          if (this.countdown > 0) {
            this.countdown--;
          }
        }, 1000);
        this.noticeDialogVisible = true;
      },

    // 修改 closeNotice 方法，支持内容不足一屏时直接关闭
    closeNotice() {
      if (this.countdown > 0) {
        this.$message.warning('请先阅读通知满 30 秒');
        return;
      }

      // 检查是否所有行都已勾选
      const allChecked = this.checkedLines.every(checked => checked);
      if (!allChecked) {
        this.$message.warning('请勾选所有内容为已读');
        return;
      }

      // 关闭当前通知
      this.noticeDialogVisible = false;

      // 显示下一条通知
      this.currentNoticeIndex++;
      if (this.currentNoticeIndex < this.noticeList.length) {
        this.currentNotice = this.noticeList[this.currentNoticeIndex];
        // 重新初始化通知行和选中状态
        this.initializeNoticeLines();
        this.startCountdown(); // 重新开始倒计时
        // 强制更新DOM，确保复选框状态正确显示
        this.$forceUpdate();
      } else {
        // 所有通知已读完，标记为该用户今天已读
        const userId = this.userForm.userId;
        const today = new Date().toISOString().split('T')[0];
        const storageKey = `hasViewedNotice_${userId}_${today}`;
        localStorage.setItem(storageKey, 'true');
      }
    },


    // 新增：初始化通知内容行
    initializeNoticeLines() {
      if (this.currentNotice && this.currentNotice.noticeContent) {
        // 先按换行符分割，然后再处理可能包含的HTML标签
        let lines = this.currentNotice.noticeContent.split(/\r?\n/).filter(line => line.trim() !== '');

        // 进一步处理每行，如果包含<p>标签则进一步分割
        let processedLines = [];
        lines.forEach(line => {
          // 如果行中包含<p>标签，则按<p>标签进一步分割
          if (line.includes('<p>') && line.includes('</p>')) {
            // 提取所有<p>标签中的内容
            const pContents = line.match(/<p>(.*?)<\/p>/g);
            if (pContents) {
              pContents.forEach(pTag => {
                // 去除<p>和</p>标签，只保留内容
                const content = pTag.replace(/<\/?p>/g, '');
                if (content.trim() !== '') {
                  processedLines.push(content);
                }
              });
            } else {
              // 如果没有匹配到<p>标签，直接添加行内容
              if (line.trim() !== '') {
                processedLines.push(line);
              }
            }
          } else {
            // 不包含<p>标签，直接添加
            if (line.trim() !== '') {
              processedLines.push(line);
            }
          }
        });

        this.noticeLines = processedLines;
        console.log("处理后的通知行内容", this.noticeLines);
        // 使用 Vue.set 确保响应式更新
        this.$set(this, 'checkedLines', new Array(this.noticeLines.length).fill(false));
      } else {
        this.noticeLines = [];
        this.$set(this, 'checkedLines', []);
      }
    },


    // 新增：处理行选中状态变化
    handleLineCheck(index) {
      // 由于使用了 v-model，checkbox 状态已自动更新
      // 这里可以添加其他需要在选中状态改变时执行的逻辑
      console.log(`Line ${index} checked status: ${this.checkedLines[index]}`);
    },


      // 示例方法：获取用户信息
    getUserInfo() {
      getUserProfile().then(response => {
        this.userForm = response.data;
        this.getPlans(); // 先加载招聘计划
        this.loadNotices(); // 新增：加载通知
      });
    },
    /** 获取所有有效的招聘计划 */
    getPlans() {
      listPlan({pageNum: 1, pageSize: 9999}).then(response => {
        const now = new Date();
        this.allPlans = response.rows;
        this.activePlans = response.rows.filter(plan => {
          if (plan.status !== '0') return false;
          if (!plan.registrationDeadline) return false;
          const deadline = new Date(plan.registrationDeadline);
          return deadline > now;
        });

        // 如果存在有效计划，默认选择第一个
        if (this.activePlans.length > 0) {
          this.selectedPlanId = this.activePlans[0].planId;
          this.handlePlanChange(this.selectedPlanId); // 触发岗位筛选
        }
      });
    },


    handleMyApply() {
      // this.getMyApplyList();
      if(this.applyInfo.applyId != null){
        this.applyDialogVisible = true;
      } else {// 报名申请已取消
        this.$modal.msgError("您还没有报名申请");
      }
    },
    // 取消报名申请
    cancelMyApply() {
      this.applyDialogVisible = false;
      delApplyByID(this.applyInfo.applyId).then(response => {
        this.$modal.msgSuccess("报名申请已取消");// 报名申请已取消
        const params = {
          instanceId: response.data
        }
        stopProcess(params).then( res => {
          this.$modal.msgSuccess(res.msg);
          this.getList();
        });

        this.getMyApplyList()
      })
    },

    // 获取我的报名信息
    getMyApplyList() {
      this.getpermit();

      this.resetapplyInfo();
      const idcard = this.userForm.idcard;
      const batchNumber = this.queryParams.batchNumber;
      if (!batchNumber) {
        this.$modal.msgError("请先选择招聘计划");
        return;
      }
      const formdata = {idcard: idcard, batchNumber: batchNumber};
      console.log("身份信息：" + idcard, "批次编号：" + batchNumber);

      // 调用接口查询报名信息
      getApplyByIdcardAndBatchNumber(formdata).then(response => {
        console.log("报名信息：" , response);

        if (response.data && response.data.length > 0) {
          this.applyInfo = response.data[0]; // 取第一条记录

        } else {
          this.$modal.msg("当前未查询到报名信息");
        }
      }).catch(error => {
        this.$modal.msgError("查询报名信息失败");
        console.error("获取报名信息失败:", error);
      });
    },


    /**
     * 处理招聘计划选择变化
     */
    handlePlanChange(planId) {
      if (!planId) {
        this.availableList = [];
        this.updatePaginatedAll();
        return;
      }

      const selectedPlan = this.allPlans.find(p => p.planId === planId);
      if (selectedPlan) {
        // 筛选岗位列表中与所选招聘计划批次号相同的岗位
        this.queryParams.batchNumber = selectedPlan.batchNumber;
        this.handleQuery(); // 触发查询
      }
    }
    ,
    /** 查询招聘岗位信息列表 */
    getList() {
      this.queryParams.pageNum = 1,
      this.queryParams.pageSize = 9999;
      this.loading = true;
       console.info('查询参数：', this.queryParam);
      listAvailable(this.queryParams).then(response => {
        this.availableList = response.rows;
        this.total = response.total;
        console.log("availableList:" + this.availableList.length)
        this.loading = false;
        this.queryParams.pageSize = 30;
        this.updatePaginatedAll(); // 初始化分页数据
      });
    },

    // 切换 Tab 时更新分页
    handleTabClick(tab) {
      this.queryParams.pageNum = 1; // 切换 tab 时重置为第一页
      this.$nextTick(() => {
        if (tab.name === 'all') {
          this.updatePaginatedAll(); // 更新全部岗位数据
        }
      });
    },
    // 新增：处理分页变化
    handlePaginationChange() {
      this.$nextTick(() => {
        if (this.activeTab === 'all') {
          this.updatePaginatedAll();
        }
      });
    },

    // 更新全部岗位分页数据
    updatePaginatedAll() {
      // this.queryParams.pageSize = 30;
      const start = (this.queryParams.pageNum - 1) * this.queryParams.pageSize;
      const end = start + this.queryParams.pageSize;
      this.paginatedAll = this.availableList.slice(start, end);
      this.totalAll = this.availableList.length;
    },


    // 分类岗位分页
    paginatedCategory(jobs) {
      const start = (this.queryParams.pageNum - 1) * this.queryParams.pageSize;
      const end = start + this.queryParams.pageSize;
      return jobs.slice(start, end);
    },


    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    resetapplyInfo() {
      this.applyInfo = {
        applyId: null,
        positionCode: null,
        positionName: null,
        companyName: null,
        location: null,
        batchNumber: null,
        applyTime: null
      };
      // this.resetForm("applyInfo");
    },
    reset() {
      this.form = {
        positionId: null,
        positionCode: null,
        companyName: null,
        positionName: null,
        positionNumber: null,
        ageLimit: null,
        requiredSex: null,
        positionSort: null,
        positionNature: null,
        salary: null,
        minSalary:null,
        maxSalary:null,
        educationaRequirements: null,
        location: null,
        requiredMajor: null,
        requiredLevel: null,
        workExperienceRequirements: null,
        batchNumber: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        otherRequirements: null,
        contactPhone: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;

      // 处理年龄筛选 - 用户输入具体年龄，匹配数据库中的年龄要求
      // 保留原始ageLimit用于显示
      const originalAgeLimit = this.queryParams.ageLimit;
      // 例如：用户输入年龄25，需要匹配数据库中"25以上"、"20-30之间"等规则
      if (this.queryParams.ageLimit && !isNaN(this.queryParams.ageLimit)) {
        // 如果用户输入的是具体年龄数字，则保存为查询参数
        this.queryParams.userAge = parseInt(this.queryParams.ageLimit);

        // 清空ageLimit避免冲突
        this.queryParams.ageLimit = '';
      }

      this.getList();
      this.queryParams.ageLimit = originalAgeLimit;
      this.getMyApplyList();
    },
    /** 重置按钮操作 */
    resetQuery() {

      const savedBatchNumber = this.queryParams.batchNumber;

      if (this.$refs.queryForm) {
          this.$refs.queryForm.resetFields();
        }
      this.queryParams.batchNumber = savedBatchNumber;
      this.queryParams.minSalary = null;
      this.queryParams.maxSalary = null;
      this.handleQuery();
    },

    /** 报名按钮操作 */
    handleApply(row) {

      this.getFlowFormData(this.deployId);
      this.form = {row}; // 深拷贝岗位信息到 form
      this.showJobDetail(row);
    },

    // 显示岗位详情对话框
    showJobDetail(job) {
      this.form = {...job}; // 深拷贝岗位信息到 form
      this.open = true; // 打开对话框

    },

    // 验证用户是否满足岗位要求
    validateUserRequirements() {
      // 1. 年龄要求验证
      if (this.form.ageLimit && this.userForm.idcard) {
        const age = this.calculateAgeFromIdCard(this.userForm.idcard);
        const ageValidationError = this.checkAgeRequirement(this.form.ageLimit, age);
        if (ageValidationError) {
          return ageValidationError;
        }
      }

      // 2. 性别要求验证
      if (this.form.requiredSex && this.userForm.sex) {
        // 岗位要求性别：0男 1女 2不限
        // 用户性别：0男 1女
        if (this.form.requiredSex !== '2' && this.form.requiredSex !== this.userForm.sex) {
          const sexText = this.form.requiredSex === '0' ? '男' : '女';
          return `性别不符合要求，岗位要求${sexText}性`;
        }
      }

      // 3. 学历要求验证
      if (this.form.educationaRequirements && this.userForm.culture) {
        if (!this.checkEducationRequirement(this.form.educationaRequirements, this.userForm.culture)) {
          return `学历不满足要求，岗位要求${this.form.educationaRequirements}，当前学历${this.userForm.culture}`;
        }
      }

      // 4. 专业要求验证
      // if (this.form.requiredMajor && this.userForm.major) {
      //   const requiredMajors = this.form.requiredMajor.split(/[,，]/);
      //   const userMajor = this.userForm.major.trim();
      //   const isMatch = requiredMajors.some(major => userMajor.includes(major.trim()));
      //   if (!isMatch) {
      //     return `专业不符合要求，岗位要求专业：${this.form.requiredMajor}`;
      //   }
      // }
      //
      // // 5. 技能等级要求验证
      // if (this.form.requiredLevel && this.userForm.level) {
      //   if (!this.checkLevelRequirement(this.form.requiredLevel, this.userForm.level)) {
      //     return `技能等级不满足要求，岗位要求${this.form.requiredLevel}及以上，当前等级${this.userForm.level}`;
      //   }
      // }

      return null; // 验证通过
    },

    // 根据身份证号计算年龄
    calculateAgeFromIdCard(idcard) {
      let birthYear, birthMonth, birthDay;

      if (idcard.length === 15) {
        birthYear = parseInt('19' + idcard.substring(6, 8));
        birthMonth = parseInt(idcard.substring(8, 10));
        birthDay = parseInt(idcard.substring(10, 12));
      } else if (idcard.length === 18) {
        birthYear = parseInt(idcard.substring(6, 10));
        birthMonth = parseInt(idcard.substring(10, 12));
        birthDay = parseInt(idcard.substring(12, 14));
      } else {
        return -1; // 无效的身份证号
      }

      const today = new Date();
      const birthDate = new Date(birthYear, birthMonth - 1, birthDay);
      let age = today.getFullYear() - birthYear;
      const monthDiff = today.getMonth() - (birthMonth - 1);

      if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDay)) {
        age--;
      }

      return age;
    },

    // 验证学历要求
    checkEducationRequirement(requirement, userEducation) {
      // 学历层次从低到高
      const educationLevels = ['小学','初中', '高中', '大专', '本科', '硕士','博士','不限'];

      if (requirement === '不限') {
         return true;
       }
      let requiredLevel = requirement;
      if (requirement.includes('以上')) {
              requiredLevel = requirement.replace('以上', '');
           }

      const requiredIndex = educationLevels.indexOf(requiredLevel);
      const userIndex = educationLevels.indexOf(userEducation);


      return userIndex >= requiredIndex;

    },
    // 验证年龄要求的方法
    checkAgeRequirement(ageLimit, userAge) {
      // 如果是"不限"，直接通过
      if (ageLimit === '不限') {
        return null;
      }

      // 匹配"xx以上"格式，如"18以上"
      const aboveMatch = ageLimit.match(/^(\d+)以上$/);
      if (aboveMatch) {
        const minAge = parseInt(aboveMatch[1]);
        if (userAge < minAge) {
          return `年龄不符合要求，岗位要求${ageLimit}，当前年龄${userAge}岁`;
        }
        return null;
      }

      // 匹配"xx以下"格式，如"35以下"
      const belowMatch = ageLimit.match(/^(\d+)以下$/);
      if (belowMatch) {
        const maxAge = parseInt(belowMatch[1]);
        if (userAge > maxAge) {
          return `年龄不符合要求，岗位要求${ageLimit}，当前年龄${userAge}岁`;
        }
        return null;
      }

      // 匹配"xx-xx之间"格式，如"18-35之间"
      const rangeMatch = ageLimit.match(/^(\d+)-(\d+)之间$/);
      if (rangeMatch) {
        const minAge = parseInt(rangeMatch[1]);
        const maxAge = parseInt(rangeMatch[2]);
        if (userAge < minAge || userAge > maxAge) {
          return `年龄不符合要求，岗位要求${ageLimit}，当前年龄${userAge}岁`;
        }
        return null;
      }

      // 匹配具体年龄数值，如"30"
      const exactMatch = ageLimit.match(/^(\d+)$/);
      if (exactMatch) {
        const requiredAge = parseInt(exactMatch[1]);
        if (userAge !== requiredAge) {
          return `年龄不符合要求，岗位要求${requiredAge}岁，当前年龄${userAge}岁`;
        }
        return null;
      }

      // 如果格式不匹配任何规则，返回错误
      return `年龄要求格式不正确：${ageLimit}`;
    },

    // 验证技能等级要求
    checkLevelRequirement(requirement, userLevel) {
      // 技能等级从低到高（根据实际情况可能需要调整）
      const levelOrder = ['初级', '中级', '高级', '四级', '三级', '二级', '一级'];

      // 如果岗位要求为"二级"，则一级、二级都符合要求
      // 如果岗位要求为"中级"，则中级、高级都符合要求

      const requiredIndex = levelOrder.indexOf(requirement);
      const userIndex = levelOrder.indexOf(userLevel);

      // 如果找不到对应的等级，尝试模糊匹配
      if (requiredIndex === -1 || userIndex === -1) {
        // 简单包含关系判断
        return userLevel.includes(requirement) || requirement.includes(userLevel) || userLevel === requirement;
      }

      // 用户等级必须高于或等于要求等级
      return userIndex >= requiredIndex;
    },




    /** 提交按钮 */
    submitForm() {
      if (this.form.positionId != null) {
        this.$refs.vFormRef.getFormData().then(formData => {

          console.log("form1" + this.form.positionId);

          // 验证用户是否满足岗位要求
          const validationError = this.validateUserRequirements();
          if (validationError) {
            this.$modal.msgError(validationError);
            return;
          }

          if (this.haspermit===4) {
            this.$alert('当前批次，你已有报名申请，请先到报名申请菜单取消当前申请，再进行下步操作！！！', '警告', {
              confirmButtonText: '确定',
              type: 'warning',
              callback: action => {
                // 用户点击“确定”后可执行的操作
                this.open = false;
                // this.handleMyApply();
              }
            });
            return;
          } else if (this.haspermit===0){

            this.formData = formData;

            // 启动流程并将表单数据加入流程变量

            let procDefId = this.procDefId;
            let deployId = this.deployId;
            const params = {deployId: deployId}
            flowFormData(params).then(res1 => {
              const param = {formJson: res1.data,};
              // 复制对象的属性值给新的对象
              Object.assign(param, this.formData);

              definitionStart(procDefId, param).then(res => {
                this.$modal.msgSuccess(res.msg);
                this.getMyApplyList();
                // this.goBack();
                this.open = false;
              })
            }).catch(res1 => {
              // this.goBack();
              this.open = fa
            })
          }else if (this.haspermit===3){
            this.$alert('修改报名超过5次！请联系管理员', '警告',);
          }

        }).catch(error => {
          // this.$modal.msgError(error)
        })
      }
    },
    getpermit(){
      haspermit().then(res => {
        if (res.code === 200 ) {
          this.haspermit = res.data;}
        else {
          this.$message.error(res.msg);}
        console.info("permit:" + res.msg)
      })
    },

    handleClick(tab, event) {
      if (tab.name === '2') {
        flowXmlAndNode({deployId: this.deployId}).then(res => {
          this.flowData = res.data;
        })
      }
    },
    /** 流程表单数据 */
    getFlowFormData(deployId) {
      const params = {deployId: deployId}
      flowFormData(params).then(res => {
        // 流程过程中不存在初始化表单 直接读取的流程变量中存储的表单值
        this.$nextTick(() => {
          getUserProfile().then(response => {
            // 回显数据
            this.$refs.vFormRef.setFormJson(res.data);
            this.formJson = res.data;

            const a = this.form;
            Object.assign(a, response.data);

            this.formRenderData = a;

          })

        })
      }).catch(res => {
        this.goBack();
      })
    },
    /** 返回页面 */
    goBack() {
      // 关闭当前标签页并返回上个页面
      const obj = {path: "/", query: {t: Date.now()}};
      this.$tab.closeOpenPage(obj);
    },

    /** 重置表单 */
    resetForm() {
      this.$refs.vFormRef.resetForm();
    },
    close(){
      this.open = false; // 关闭对话框
    },
    /** 提交流程 */
    submitTask() {
      if (!this.checkValues && this.checkSendUser) {
        this.$modal.msgError("请选择任务接收!");
        return;
      }
      if (!this.checkValues && this.checkSendRole) {
        this.$modal.msgError("请选择流程接收角色组!");
        return;
      }
      if (this.formData) {
        const param = {
          formJson: this.formJson,
        }
        // 复制对象的属性值给新的对象
        Object.assign(param, this.formData);
        if (this.multiInstanceVars) {
          this.$set(param, this.multiInstanceVars, this.checkValues);
        } else {
          this.$set(param, "approval", this.checkValues);
        }
        // 启动流程并将表单数据加入流程变量
        definitionStart(this.procDefId, param).then(res => {
          this.$modal.msgSuccess(res.msg);
          this.goBack();
        })
      }
    },
    // 用户信息选中数据
    handleUserSelect(selection) {
      if (selection) {
        if (selection instanceof Array) {
          const selectVal = selection.map(item => item.userId);
          if (this.multiInstanceVars) {
            this.checkValues = selectVal;
          } else {
            this.checkValues = selectVal.join(',');
          }
        } else {
          this.checkValues = selection.userId;
        }
      }
    },
    // 角色信息选中数据
    handleRoleSelect(selection) {
      if (selection) {
        if (selection instanceof Array) {
          const selectVal = selection.map(item => item.roleId);
          this.checkValues = selectVal.join(',')
        } else {
          this.checkValues = selection;
        }
      }
    },

  },
  beforeDestroy() {
    if (this.noticeTimer) {
      clearInterval(this.noticeTimer);
    }
  },
  mounted() {
    // this.handleScroll(); // 初始化判断内容高度
  },
  computed: {
    categorizedJobs() {
      const result = {};
      this.availableList.forEach(job => {
        const key = job.positionNature || '未知';
        if (!result[key]) {
          result[key] = [];
        }
        result[key].push(job);
      });
      return result;
    }
  }
};
</script>

<style scoped>
.form-item-align ::v-deep .el-form-item__content,
.form-item-align ::v-deep .el-form-item__label {
  display: flex;
  align-items: center;
  height: 36px;
  line-height: 20px;
  margin-bottom: 0;
}

.form-item-align ::v-deep .el-form-item__label {
  padding-right: 10px;
}

.job-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 30px;
}

.job-card {
  width: 300px;
  height: 150px;
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-radius: 10px; /* 四个角圆角 */
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 10px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  transition: all 0.3s ease;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.card-header .job-salary {
  color: red;
  font-weight: bold;
  margin-left: 10px;
}

.card-body {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  margin-top: 5px;
}

.card-body .badge {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 2px 6px;
  font-size: 16px;
  color: #666;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f0f9eb; /* 淡绿色背景 */
  padding: 5px 8px;
  font-size: 16px;
  color: #333;
  border-top: 1px solid #ebeef5;
  border-bottom-left-radius: 8px;
  border-bottom-right-radius: 8px;
}


.job-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 20px 0 rgba(0, 0, 0, 0.15);
}

@media (max-width: 1200px) {
  .job-card {
    width: calc(33.33% - 15px);
  }
}

@media (max-width: 992px) {
  .job-card {
    width: calc(50% - 15px);
  }
}

@media (max-width: 768px) {
  .job-card {
    width: 100%;
  }
}

.job-code {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
  margin-right: 10px;
}

.job-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 5px;
}

.job-description {
  font-size: 14px;
  color: #888;
  margin-bottom: 10px;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.card-footer .el-button {
  padding: 5px 10px;
  font-size: 12px;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.card-footer .el-button {
  padding: 5px 10px;
  font-size: 12px;
}

.card-footer .el-button:hover {
  background-color: #409eff;
  color: #fff;
}

.card-footer .el-button.is-disabled {
  background-color: #f5f7fa;
  color: #c0c4cc;
  cursor: not-allowed;
}

.card-footer .el-button.is-disabled:hover {
  background-color: #f5f7fa;
}
.notice-dialog .el-dialog__body {
  padding: 20px;
  font-size: 16px;
}

.notice-dialog .notice-content h3 {
  margin-top: 0;
  color: #333;
}

.notice-dialog .notice-content p {
  margin: 20px 0;
  line-height: 1.6;
  color: #555;
}

.notice-dialog .countdown {
  font-size: 14px;
  color: #999;
  text-align: right;
}
.notice-dialog .notice-content {
  max-height: 60vh;
  overflow-y: hidden;
  display: flex;
  flex-direction: column;
}

.notice-dialog .notice-body {
  flex: 1;
  overflow-y: auto;
  font-size: 16px;
  line-height: 1.6;
  color: #555;
  margin-top: 10px;
  padding-right: 10px;
  max-height: 400px;
  width: 100%;
}

/* 新增：通知行样式 */
.notice-dialog .notice-line {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
  width: 100%;
  word-wrap: break-word;
  word-break: break-word;
}

.notice-dialog .notice-checkbox {
  width: 100%;
  white-space: normal;
  display: flex;
  align-items: flex-start;
}

.notice-dialog .notice-line-content {
  white-space: pre-wrap;
  word-wrap: break-word;
  word-break: break-word;
  flex: 1;
  margin: 0;
  padding: 0;
}

.notice-dialog .progress-info {
  margin: 10px 0;
  font-size: 14px;
  color: #666;
  text-align: center;
}

.notice-dialog .countdown {
  margin: 10px 0;
  font-size: 14px;
  color: #999;
  text-align: center;
}

.notice-dialog .manual-close {
  text-align: center;
  margin-top: 10px;
}

</style>
